package edu.cn.nlsde.Utils; /**
 * @date 2015年12月15日 下午4:41:07
 * @version V1.0
 */

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ffftzh
 * @ClassName: Utils
 * @Description: 一些工具
 * @date 2015年12月15日 下午4:41:07
 */
public class Utils {
    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
    final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");

    public static String join(String[] array, String separator) {
        StringBuffer result = new StringBuffer();
        int tag = 0;
        for (String string : array) {
            if (tag > 0) {
                result.append(separator);
            }
            tag = 1;
            result.append(string);
        }
        return result.toString();
    }

    public static String join(int[] array, String separator) {
        StringBuffer result = new StringBuffer();
        int tag = 0;
        for (int string : array) {
            if (tag > 0) {
                result.append(separator);
            }
            tag = 1;
            result.append(String.format("%d", string));
        }
        return result.toString();
    }

    public static String join(double[] array, String separator) {
        StringBuffer result = new StringBuffer();
        int tag = 0;
        for (double string : array) {
            if (tag > 0) {
                result.append(separator);
            }
            tag = 1;
            result.append(String.format("%.2f", string));
        }
        return result.toString();
    }

    public static String join(List<String> array, String separator) {
        StringBuffer result = new StringBuffer();
        int tag = 0;
        for (String string : array) {
            if (tag > 0) {
                result.append(separator);
            }
            tag = 1;
            result.append(string);
        }
        return result.toString();
    }

    public static String join(ArrayList<String> array, String separator) {
        StringBuffer result = new StringBuffer();
        int tag = 0;
        for (String string : array) {
            if (tag > 0) {
                result.append(separator);
            }
            tag = 1;
            result.append(string);
        }
        return result.toString();
    }

    /**
     * @param @param  new_corpus
     * @param @return
     * @return ArrayList<ArrayList<String>>
     * @throws
     * @Title: hash2Array
     * @Description: 把hashMap转换成Array
     */
    public static ArrayList<?> hash2Array(HashMap<?, ?> new_corpus) {
        ArrayList<Object> result = new ArrayList<Object>();
        for (Object item : new_corpus.values()) {
            result.add(item);
        }
        return result;
    }

    /**
     * @param @param  tassignPath
     * @param @return
     * @return String
     * @throws
     * @Title: get_parent_path
     * @Description: 找到一个文件的父目录
     */
    public static String get_parent_path(String tassignPath) {
        File tmp = new File(tassignPath);
        return tmp.getParentFile().getAbsolutePath();
    }

    public static void correct_phi() throws IOException {
        for (int ki = 0; ki < 10; ki++) {
            int V = 12516;
            String rootpath = "D:\\javaEE\\MLDA\\data\\yahoo_answers\\PAM4ST\\1000_100\\" + ki + "\\";
            BufferedReader reader = IOUtil.getReader(rootpath + "phi.txt");
            BufferedWriter writer = IOUtil.getWriter(rootpath + "phi_final.txt");
            String line = reader.readLine();
            while (line != null) {
                String segs[] = line.split("\\s+");
                for (int k = 0; k != 100; k++) {
                    int from, to;
                    from = k * V;
                    to = k * V + V;
                    String[] out = Arrays.copyOfRange(segs, from, to);
                    for (String str : out) {
                        writer.append(str + " ");
                    }
                    writer.newLine();
                }
                writer.close();
                line = reader.readLine();
            }
            reader.close();
        }
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            System.out.println(urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }

    public static ArrayList<ArrayList<String>> findByRegex(String regex, String text) {
        ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(text);
        while (m.find()) {
            ArrayList<String> oneLine = new ArrayList<String>();
            int num = m.groupCount();
            for (int i = 1; i <= num; i++) {
                oneLine.add(m.group(i));
            }
            result.add(oneLine);
        }
        return result;
    }

    public static String Calculate_identity(String itemString) {
        String result = null;
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            result = bytesToHex(md.digest(itemString.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    public static String Date2String(Date date) {
        String format = "yyyy-MM-dd HH:mm:ss";
        return Date2String(date, format);
    }

    public static String Date2String(Date date, String format) {
        SimpleDateFormat dateformat1 = new SimpleDateFormat(format);
        return dateformat1.format(date);
    }

    public static Date String2Date(String created_at, String format) throws ParseException {
        DateFormat formator = new SimpleDateFormat(format, Locale.ENGLISH);
        return formator.parse(created_at);
    }

    public static String generate_DateTime_Filename() {
        return sdf.format(new Date()) + "_" + Math.round(Math.random() * 10000);
    }

}
